package com.develop.wechatpay.handler;

import com.alibaba.fastjson.JSONObject;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 请求参数校验传递的json格式参数校验
     *
     * @param req
     * @param exception
     * @return
     * @throws Exception
     * @author khy
     * @createTime 2021年5月18日下午5:24:55
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Object validatedPostException(HttpServletRequest req, MethodArgumentNotValidException exception) {
        JSONObject json = new JSONObject();
        BindingResult bindingResult = exception.getBindingResult();
        json.put("code", 500);
        json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        json.put("msg", "");
        if (bindingResult.hasErrors()) {
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            List<String> errorList = fieldErrors.stream().map(e -> e.getDefaultMessage()).collect(Collectors.toList());
            Map<String, String> errorMap = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            if (errorMap != null && errorMap.size() >= 1) {
                String messageError = "";
                for (String key : errorMap.keySet()) {
                    messageError = messageError + errorMap.get(key) + "[" + key + "],";
                }
                messageError = messageError.substring(0, messageError.length() - 1);
                json.put("msg", messageError);
            }
        }
        return json;
    }

    /**
     * 普通的参数传递的形式;
     *
     * @param req
     * @param exception
     * @return
     * @throws Exception
     * @author khy
     * @createTime 2021年5月18日下午5:25:16
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Object validatedGetException(HttpServletRequest req, BindException exception) {
        JSONObject json = new JSONObject();
        json.put("code", 500);
        json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        json.put("msg", "");
        if (exception.hasErrors()) {
            List<FieldError> fieldErrors = exception.getFieldErrors();
            List<String> errorList = fieldErrors.stream().map(e -> e.getDefaultMessage()).collect(Collectors.toList());
            Map<String, String> errorMap = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            if (errorMap != null && errorMap.size() >= 1) {
                String messageError = "";
                for (String key : errorMap.keySet()) {
                    messageError = messageError + errorMap.get(key) + "[" + key + "],";
                }
                messageError = messageError.substring(0, messageError.length() - 1);
                json.put("msg", messageError);
            }
        }
        return json;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object exception(HttpServletRequest req, Exception e) throws Exception {
        JSONObject json = new JSONObject();
        json.put("code", 500);
        json.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        json.put("msg", e.getMessage());
        return json;
    }
}

